package dao.impl;

import common.DBConnector;
import common.EntityChange;
import dao.dai.UserDao;
import entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserImpl implements UserDao {
    private final Connection conn = DBConnector.getSQLServerConnection();

    @Override
    public User search(String uId) throws SQLException {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM [User] WHERE uId=?");
        preparedStatement.setString(1,uId);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next())return EntityChange.UserChange(resultSet);
        else return null;
    }

    @Override
    public boolean insert(String uId, String pwd) throws SQLException {
        if (uId!=null&&pwd!=null){
            PreparedStatement preparedStatement = conn.prepareStatement("Insert INTO [User] VALUES(?,?)");
            preparedStatement.setString(1,uId);
            preparedStatement.setString(2,pwd);
            preparedStatement.execute();
            return true;
        }else return false;
    }

    @Override
    public boolean update(String uId, String pwd) throws SQLException {
        if (uId!=null&&pwd!=null){
            PreparedStatement preparedStatement = conn.prepareStatement("UPDATE [User] SET uPwd=? WHERE uId =?");
            preparedStatement.setString(1,pwd);
            preparedStatement.setString(2,uId);
            preparedStatement.execute();
            return true;
        }else return false;
    }
}
